In this tutorial, we will learn how to replace characters or substrings in a string using Vue.js and the replace()
and replaceAll()
methods. In the first example, we use the Vue.js replace
method with regex to replace a part of a string with another substring or character. In the second example, we use the Vue.js replaceAll
method to search and replace characters in a string.
Vue Replace Character in String ?
This is the first example of this tutorial where we demonstrate how to replace all occurrences of a substring in a string. We use replace()
and regex with Vue.js to complete this task.
Vue Substring Replace in String
<script type="module">
import {createApp} from 'vue'
createApp({
data() {
return {
string: 'This is an awesome site that provides icons and tutorials for Vue and React. The sites name is Fontawesomeicons',
character: 'website',
results: ''
}
},
methods: {
myFunction() {
// Replace all occurrences of 'site' with 'website' in 'string'
this.results = this.string.replace(/site/g, this.character);
}
}
}).mount('#app')
</script>
Output of Replacements of String in Vue Javascript
In the example below, we utilize the replaceAll() method to achieve the same functionality as covered in the above example.
Vue Js String Replace All
<script type="module">
import {createApp} from 'vue'
createApp({
data() {
return {
string: 'This is an awesome site that provides icons and tutorials for Vue and React. The sites name is Fontawesomeicons',
character: 'website',
results: ''
}
},
methods: {
myFunction() {
// Replace all occurrences of 'site' with 'website' in 'string'
this.results = this.string.replaceAll('site', this.character);
}
}
}).mount('#app')
</script>